﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.propertytype;
using umbraco.interfaces;
using System.Collections;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.property;
using AjaxControlToolkit;
using umbraco.cms.businesslogic;
using System.Net.Mail;
using System.Text;

namespace osMemberControls
{
    public partial class MemberProfile : System.Web.UI.UserControl
    {
        private string _beforeRow = "<tr>";
        private string _afterRow = "</tr>";
        private string _beforeCell = "<td>";
        private string _afterCell = "</td>";
        private string _beforeCellRight = "<td align=\"right\">";
        private string _startTable = "<table id=\"osMemberProfile\">";
        private string _endTable = "</table>";
        private ArrayList _dataFields = new ArrayList();
        private int _redirect;
        private int _tabtoshow;
        private bool _singletab;
        private bool _showastablayout;
        private bool _allowemailupdate;
        private string _requiredEmail;
        private string _passworddidntmatch;
        private AjaxControlToolkit.TabContainer tc;
        private bool _showgenericproperties;
        private string _buttontext;
        private bool _allowpasswordupdate;
        private bool _emailonupdate;
        private string _emailto;
        private string _emailsubject;


        public bool ShowSingleTab
        {
            get { return _singletab; }
            set { _singletab = value; }
        }

        public int TabToShow
        {
            get { return _tabtoshow; }
            set { _tabtoshow = value; }
        }

        public int RedirectOnSuccess
        {
            get { return _redirect; }
            set { _redirect = value; }
        }

        public bool ShowAsTabLayout
        {
            get { return _showastablayout; }
            set { _showastablayout = value; }
        }

        public bool AllowEmailUpdate
        {
            get { return _allowemailupdate; }
            set { _allowemailupdate = value; }
        }

        public string EmailRequiredMessage
        {
            get { return _requiredEmail; }
            set { _requiredEmail = value; }
        }

        public bool ShowGenericProperties
        {
            get { return _showgenericproperties; }
            set { _showgenericproperties = value; }
        }

        public string ButtonText
        {
            get { return _buttontext; }
            set { _buttontext = value; }
        }

        public bool AllowPasswordUpdate
        {
            get { return _allowpasswordupdate; }
            set { _allowpasswordupdate = value; }
        }

        public string ErrorPasswordsDidntMatch
        {
            get { return _passworddidntmatch; }
            set { _passworddidntmatch = value; }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            ((umbraco.UmbracoDefault)this.Page).ValidateRequest = false;

        }

        public bool EmailAdminOnUpdate
        {
            get { return _emailonupdate; }
            set { _emailonupdate = value; }
        }

        public string AdminEmailAddress
        {
            get { return _emailto; }
            set { _emailto = value;}
        }

        public string EmailSubject
        {
            get { return _emailsubject; }
            set { _emailsubject = value; }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            Member m = Member.GetMemberFromLoginName(HttpContext.Current.User.Identity.Name);
            umbraco.cms.businesslogic.member.MemberType mt = new umbraco.cms.businesslogic.member.MemberType(m.ContentType.Id);
            IEnumerable<PropertyType> ptypes;

            //Show a single tab from member type properties
            if (_singletab == true)
            {
                ptypes = mt.PropertyTypes.Where(pt => pt.TabId == _tabtoshow);
            }
            //show properties from multiple tabs
            else
            {
                ptypes = mt.PropertyTypes;
                if (_showgenericproperties == false)
                {
                    ptypes = ptypes.Where(g => g.TabId != 0);
                }
            }
            
            //should the page be shown in tabs or a single page layout
            if (_showastablayout == true)
            {
                tc = new TabContainer();
                tc.ID = "tc1";
                AjaxControlToolkit.TabPanelCollection tpc = new TabPanelCollection(tc);

                //see if are showing only one tab from member type properties
                if (_singletab != true)
                {
                    if (_showgenericproperties == true)
                    {
                        AjaxControlToolkit.TabPanel tpGP = new TabPanel();
                        tpGP.ID = "0";
                        tpGP.HeaderText = "Generic Properties";
                        tpGP.Controls.Add(new LiteralControl(_startTable));
                        tc.Tabs.Add(tpGP);
                    }

                    //loop through all the tabs in the membertype and create a TabPabel
                    foreach (umbraco.cms.businesslogic.ContentType.TabI t in mt.getVirtualTabs)
                    {
                        AjaxControlToolkit.TabPanel tp = new TabPanel();
                        tp.ID = t.Id.ToString();
                        tp.HeaderText = t.Caption;
                        tp.Controls.Add(new LiteralControl(_startTable));
                        tc.Tabs.Add(tp);
                    }
                }
                //showing tab layout but only showing single tab from membertype
                else
                {
                    if (_tabtoshow == 0)
                    {
                        AjaxControlToolkit.TabPanel tpGP = new TabPanel();
                        tpGP.ID = "0";
                        tpGP.HeaderText = "Generic Properties";
                        tpGP.Controls.Add(new LiteralControl(_startTable));
                        tc.Tabs.Add(tpGP);
                    }
                    else
                    {
                        //loop through tabs in membertype and find one we want to show
                        foreach (umbraco.cms.businesslogic.ContentType.TabI t in mt.getVirtualTabs)
                        {
                            if (t.Id == _tabtoshow)
                            {
                                AjaxControlToolkit.TabPanel tp = new TabPanel();
                                tp.ID = t.Id.ToString();
                                tp.HeaderText = t.Caption;
                                tp.Controls.Add(new LiteralControl(_startTable));
                                tc.Tabs.Add(tp);
                            }
                        }
                    }
                }

                ph1.Controls.Add(tc);
                //because email is not a property on the tabs we need to add it manaully to the first tab
                //or first control if single page layout
                AddEmailControl(tc.Tabs[0], m);
                AddPasswordControl(tc.Tabs[0], m);

                #region Tab Layout
                //loop through property types and add them to the page
                foreach (PropertyType pt in ptypes)
                {
                    //check to make sure this should be visible to the member
                    if (mt.ViewOnProfile(pt) == true)
                    {
                        TabPanel tp = new TabPanel();

                        foreach (TabPanel p in tc.Tabs)
                        {
                            if (p.ID.ToString() == pt.TabId.ToString())
                            {
                                tp = p;
                            }
                        }

                        tp.Controls.Add(new LiteralControl(_beforeRow));
                        tp.Controls.Add(new LiteralControl(_beforeCellRight));


                        IDataType dt = pt.DataTypeDefinition.DataType;
                        dt.DataEditor.Editor.ID = pt.Alias;
                        dt.Data.Value = m.getProperty(pt.Alias.ToString()).Value;

                        if (mt.MemberCanEdit(pt))
                        {
                            _dataFields.Add(dt);
                        }
                        else
                        {
                            try
                            {
                                ((System.Web.UI.WebControls.WebControl)dt.DataEditor.Editor).Enabled = false;
                            }
                            catch
                            {

                            }
                        }

                        Label l = new Label();
                        l.ID = "lbl" + pt.Alias;
                        l.AssociatedControlID = dt.DataEditor.Editor.ID;
                        l.Text = pt.Name + ":";


                        tp.Controls.Add(l);
                        tp.Controls.Add(new LiteralControl(_afterCell));

                        tp.Controls.Add(new LiteralControl(_beforeCell));
                        tp.Controls.Add(dt.DataEditor.Editor);

                        // Validation
                        if (pt.Mandatory)
                        {
                            try
                            {
                                RequiredFieldValidator rq = new RequiredFieldValidator();
                                rq.ID = dt.DataEditor.Editor.ID + "_RFV";
                                rq.ControlToValidate = dt.DataEditor.Editor.ID;
                                rq.Display = ValidatorDisplay.None;
                                rq.ValidationGroup = "this";
                                rq.ErrorMessage = "Error";
                                rq.Display = ValidatorDisplay.Dynamic;
                                rq.EnableClientScript = true;
                                tp.Controls.Add(rq);
                            }
                            catch (Exception valE)
                            {

                            }
                        }
                        // RegExp Validation
                        if (!string.IsNullOrEmpty(pt.ValidationRegExp))
                        {
                            try
                            {
                                RegularExpressionValidator rv = new RegularExpressionValidator();
                                rv.ID = dt.DataEditor.Editor.ID + "_REV";
                                rv.ControlToValidate = dt.DataEditor.Editor.ID;
                                rv.ValidationExpression = pt.ValidationRegExp;
                                rv.ValidationGroup = "this";
                                rv.ErrorMessage = "Error";
                                rv.Display = ValidatorDisplay.Dynamic;
                                rv.EnableClientScript = true;
                                rv.Display = ValidatorDisplay.None;
                                tp.Controls.Add(rv);
                            }
                            catch (Exception valE)
                            {

                            }
                        }

                        tp.Controls.Add(new LiteralControl(_afterCell));
                        tp.Controls.Add(new LiteralControl(_afterRow));
                    }

                }

                foreach (TabPanel t in tc.Tabs)
                {
                    AddButton(t);
                    t.Controls.Add(new LiteralControl(_endTable));
                }

                #endregion

            }

            else
            {

                #region Single Page

                ph1.Controls.Add(new LiteralControl(_startTable));


                if (_allowemailupdate == true)
                {
                    ph1.Controls.Add(new LiteralControl(_beforeRow));

                    ph1.Controls.Add(new LiteralControl(_beforeCellRight));

                    Label l = new Label();
                    l.ID = "lbl" + "txtEmail";
                    l.AssociatedControlID = "txtEmail";
                    l.Text = "Email" + ":";


                    ph1.Controls.Add(l);
                    ph1.Controls.Add(new LiteralControl(_afterCell));

                    ph1.Controls.Add(new LiteralControl(_beforeCell));
                    TextBox txtEmail = new TextBox();
                    txtEmail.ID = "txtEmail";
                    txtEmail.CssClass = "umbEditorTextField";
                    txtEmail.Text = m.Email.ToString();
                    ph1.Controls.Add(txtEmail);

                    RequiredFieldValidator rfv = new RequiredFieldValidator();
                    rfv.ID = "rfv_Email";
                    rfv.ControlToValidate = txtEmail.ID;
                    rfv.ErrorMessage = _requiredEmail;
                    rfv.Display = ValidatorDisplay.None;
                    rfv.ValidationGroup = "this";
                    rfv.Display = ValidatorDisplay.Dynamic;
                    rfv.EnableClientScript = true;
                    ph1.Controls.Add(rfv);

                    ph1.Controls.Add(new LiteralControl(_afterCell));
                    ph1.Controls.Add(new LiteralControl(_afterRow));
                }

                if (_allowpasswordupdate == true)
                {
                    ph1.Controls.Add(new LiteralControl(_beforeRow));
                    ph1.Controls.Add(new LiteralControl(_beforeCellRight));

                    Label l = new Label();
                    l.ID = "lbl" + "txtPassword";
                    l.AssociatedControlID = "txtPassword";
                    l.Text = "New Password" + ":";


                    ph1.Controls.Add(l);
                    ph1.Controls.Add(new LiteralControl(_afterCell));

                    ph1.Controls.Add(new LiteralControl(_beforeCell));
                    TextBox txtPassword = new TextBox();
                    txtPassword.ID = "txtPassword";
                    txtPassword.Text = "";
                    txtPassword.TextMode = TextBoxMode.Password;
                    ph1.Controls.Add(txtPassword);


                    ph1.Controls.Add(new LiteralControl(_afterCell));
                    ph1.Controls.Add(new LiteralControl(_afterRow));

                    ph1.Controls.Add(new LiteralControl(_beforeRow));
                    ph1.Controls.Add(new LiteralControl(_beforeCellRight));

                    Label l2 = new Label();
                    l2.ID = "lbl" + "txtPasswordConfirm";
                    l2.AssociatedControlID = "txtPasswordConfirm";
                    l2.Text = "Confirm New Password" + ":";


                    ph1.Controls.Add(l2);
                    ph1.Controls.Add(new LiteralControl(_afterCell));

                    ph1.Controls.Add(new LiteralControl(_beforeCell));
                    TextBox txtPasswordConfirm = new TextBox();
                    txtPasswordConfirm.ID = "txtPasswordConfirm";
                    txtPasswordConfirm.Text = "";
                    txtPasswordConfirm.TextMode = TextBoxMode.Password;
                    ph1.Controls.Add(txtPasswordConfirm);


                    ph1.Controls.Add(new LiteralControl(_afterCell));
                    ph1.Controls.Add(new LiteralControl(_afterRow));

                    CompareValidator rfv = new CompareValidator();
                    rfv.ID = "rfv_Password";
                    rfv.ControlToValidate = txtPasswordConfirm.ID;
                    rfv.ErrorMessage = _passworddidntmatch;
                    rfv.ControlToCompare = txtPassword.ID;
                    rfv.Display = ValidatorDisplay.None;
                    rfv.ValidationGroup = "this";
                    rfv.Display = ValidatorDisplay.Dynamic;
                    rfv.EnableClientScript = true;
                    ph1.Controls.Add(rfv);
                }


                foreach (PropertyType pt in ptypes)
                {

                    if (mt.ViewOnProfile(pt) == true)
                    {

                        ph1.Controls.Add(new LiteralControl(_beforeRow));
                        ph1.Controls.Add(new LiteralControl(_beforeCellRight));


                        IDataType dt = pt.DataTypeDefinition.DataType;
                        dt.DataEditor.Editor.ID = pt.Alias;
                        dt.Data.Value = m.getProperty(pt.Alias.ToString()).Value;

                        if (mt.MemberCanEdit(pt))
                        {
                            _dataFields.Add(dt);
                        }
                        else
                        {
                            try
                            {
                                ((System.Web.UI.WebControls.WebControl)dt.DataEditor.Editor).Enabled = false;
                            }
                            catch
                            {

                            }
                        }

                        Label l = new Label();
                        l.ID = "lbl" + pt.Alias;
                        l.AssociatedControlID = dt.DataEditor.Editor.ID;
                        l.Text = pt.Name + ":";


                        ph1.Controls.Add(l);
                        ph1.Controls.Add(new LiteralControl(_afterCell));

                        ph1.Controls.Add(new LiteralControl(_beforeCell));
                        ph1.Controls.Add(dt.DataEditor.Editor);

                        // Validation
                        if (pt.Mandatory)
                        {
                            try
                            {
                                RequiredFieldValidator rq = new RequiredFieldValidator();
                                rq.ID = dt.DataEditor.Editor.ID + "_RFV";
                                rq.ControlToValidate = dt.DataEditor.Editor.ID;
                                rq.Display = ValidatorDisplay.None;
                                rq.ValidationGroup = "this";
                                rq.ErrorMessage = "Error";
                                rq.Display = ValidatorDisplay.Dynamic;
                                rq.EnableClientScript = true;
                                ph1.Controls.Add(rq);
                            }
                            catch (Exception valE)
                            {

                            }
                        }
                        // RegExp Validation
                        if (!string.IsNullOrEmpty(pt.ValidationRegExp))
                        {
                            try
                            {
                                RegularExpressionValidator rv = new RegularExpressionValidator();
                                rv.ID = dt.DataEditor.Editor.ID + "_REV";
                                rv.ControlToValidate = dt.DataEditor.Editor.ID;
                                rv.ValidationExpression = pt.ValidationRegExp;
                                rv.ValidationGroup = "this";
                                rv.ErrorMessage = "Error";
                                rv.Display = ValidatorDisplay.Dynamic;
                                rv.EnableClientScript = true;
                                rv.Display = ValidatorDisplay.None;
                                ph1.Controls.Add(rv);
                            }
                            catch (Exception valE)
                            {

                            }
                        }

                        ph1.Controls.Add(new LiteralControl(_afterCell));
                        ph1.Controls.Add(new LiteralControl(_afterRow));
                    }

                }

                Button btnUpdateMember = new Button();
                btnUpdateMember.ID = "btnUpdateMember";
                btnUpdateMember.ValidationGroup = "this";
                btnUpdateMember.Text = _buttontext;
                btnUpdateMember.EnableViewState = true;
                btnUpdateMember.CssClass = "osBtn";

                btnUpdateMember.Click += new EventHandler(Button1_Click);


                ph1.Controls.Add(new LiteralControl(_beforeRow));
                ph1.Controls.Add(new LiteralControl(_beforeCellRight));
                ph1.Controls.Add(new LiteralControl(_afterCell));
                ph1.Controls.Add(new LiteralControl(_beforeCell));
                ph1.Controls.Add(btnUpdateMember);
                ph1.Controls.Add(new LiteralControl(_afterCell));
                ph1.Controls.Add(new LiteralControl(_afterRow));

                ph1.Controls.Add(new LiteralControl(_endTable));
                #endregion
            }


        }

        private void AddEmailControl(TabPanel c, Member m)
        {
            if (_allowemailupdate == true)
            {
                c.Controls.Add(new LiteralControl(_beforeRow));

                c.Controls.Add(new LiteralControl(_beforeCellRight));

                Label l = new Label();
                l.ID = "lbl" + "txtEmail";
                l.AssociatedControlID = "txtEmail";
                l.Text = "Email" + ":";


                c.Controls.Add(l);
                c.Controls.Add(new LiteralControl(_afterCell));

                c.Controls.Add(new LiteralControl(_beforeCell));
                TextBox txtEmail = new TextBox();
                txtEmail.ID = "txtEmail";
                txtEmail.CssClass = "umbEditorTextField";
                txtEmail.Text = m.Email.ToString();
                c.Controls.Add(txtEmail);

                RequiredFieldValidator rfv = new RequiredFieldValidator();
                rfv.ID = "rfv_Email";
                rfv.ControlToValidate = txtEmail.ID;
                rfv.ErrorMessage = _requiredEmail;
                rfv.Display = ValidatorDisplay.None;
                rfv.ValidationGroup = "this";
                rfv.Display = ValidatorDisplay.Dynamic;
                rfv.EnableClientScript = true;
                c.Controls.Add(rfv);

                c.Controls.Add(new LiteralControl(_afterCell));
                c.Controls.Add(new LiteralControl(_afterRow));
            }
        }

        private void AddPasswordControl(TabPanel c, Member m)
        {
            if (_allowpasswordupdate == true)
            {
                c.Controls.Add(new LiteralControl(_beforeRow));
                c.Controls.Add(new LiteralControl(_beforeCellRight));

                Label l = new Label();
                l.ID = "lbl" + "txtPassword";
                l.AssociatedControlID = "txtPassword";
                l.Text = "New Password" + ":";


                c.Controls.Add(l);
                c.Controls.Add(new LiteralControl(_afterCell));

                c.Controls.Add(new LiteralControl(_beforeCell));
                TextBox txtPassword = new TextBox();
                txtPassword.ID = "txtPassword";
                txtPassword.Text = "";
                txtPassword.TextMode = TextBoxMode.Password;

                c.Controls.Add(txtPassword);
                

                c.Controls.Add(new LiteralControl(_afterCell));
                c.Controls.Add(new LiteralControl(_afterRow));

                c.Controls.Add(new LiteralControl(_beforeRow));
                c.Controls.Add(new LiteralControl(_beforeCellRight));

                Label l2 = new Label();
                l2.ID = "lbl" + "txtPasswordConfirm";
                l2.AssociatedControlID = "txtPasswordConfirm";
                l2.Text = "Confirm New Password" + ":";


                c.Controls.Add(l2);
                c.Controls.Add(new LiteralControl(_afterCell));

                c.Controls.Add(new LiteralControl(_beforeCell));
                TextBox txtPasswordConfirm = new TextBox();
                txtPasswordConfirm.ID = "txtPasswordConfirm";
                txtPasswordConfirm.Text = "";
                txtPasswordConfirm.TextMode = TextBoxMode.Password;
                c.Controls.Add(txtPasswordConfirm);


                c.Controls.Add(new LiteralControl(_afterCell));
                c.Controls.Add(new LiteralControl(_afterRow));

                CompareValidator rfv = new CompareValidator();
                rfv.ID = "rfv_Password";
                rfv.ControlToValidate = txtPasswordConfirm.ID;
                rfv.ErrorMessage = _passworddidntmatch;
                rfv.ControlToCompare = txtPassword.ID;
                rfv.Display = ValidatorDisplay.None;
                rfv.ValidationGroup = "this";
                rfv.Display = ValidatorDisplay.Dynamic;
                rfv.EnableClientScript = true;
                c.Controls.Add(rfv);
            }
        }

        private void AddButton(TabPanel c)
        {
            Button btnUpdateMember = new Button();
            btnUpdateMember.ID = "btnUpdateMember";
            btnUpdateMember.ValidationGroup = "this";
            btnUpdateMember.CssClass = "osBtn";
            btnUpdateMember.Text = _buttontext;

            btnUpdateMember.Click += new EventHandler(Button1_Click);

            c.Controls.Add(new LiteralControl(_beforeRow));
            c.Controls.Add(new LiteralControl(_beforeCellRight));
            c.Controls.Add(new LiteralControl(_afterCell));
            c.Controls.Add(new LiteralControl(_beforeCell));
            c.Controls.Add(btnUpdateMember);
            c.Controls.Add(new LiteralControl(_afterCell));
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {

                if (Page.IsValid)
                {
                    Member m = Member.GetMemberFromLoginName(HttpContext.Current.User.Identity.Name);
                    umbraco.cms.businesslogic.member.MemberType mt = new umbraco.cms.businesslogic.member.MemberType(m.ContentType.Id);

                    if (_allowemailupdate == true)
                    {
                        if (_showastablayout == true)
                        {
                            TextBox txtEmail = (TextBox)tc.Tabs[0].FindControl("txtEmail");
                            m.Email = txtEmail.Text;
                            m.Save();
                        }
                        else
                        {
                            TextBox txtEmail = (TextBox)ph1.FindControl("txtEmail");
                            m.Email = txtEmail.Text;
                            m.Save();
                        }
                    }

                    if (_allowpasswordupdate == true)
                    {
                        if (_showastablayout == true)
                        {
                            TextBox txtPassword = (TextBox)tc.Tabs[0].FindControl("txtPassword");
                            TextBox txtPasswordConfirm = (TextBox)tc.Tabs[0].FindControl("txtPasswordConfirm");

                            if (!string.IsNullOrEmpty(txtPassword.Text))
                            {
                                if (txtPassword.Text == txtPasswordConfirm.Text)
                                {
                                    m.Password = txtPassword.Text;
                                }
                            }

                        }
                        else
                        {

                            TextBox txtPassword = (TextBox)ph1.FindControl("txtPassword");
                            TextBox txtPasswordConfirm = (TextBox)ph1.FindControl("txtPasswordConfirm");

                            if (!string.IsNullOrEmpty(txtPassword.Text))
                            {
                                if (txtPassword.Text == txtPasswordConfirm.Text)
                                {
                                    m.Password = txtPassword.Text;
                                }
                            }

                        }
                    }

                    foreach (umbraco.interfaces.IDataType df in _dataFields)
                    {
                        Property p = m.getProperty(df.DataEditor.Editor.ID);
                        df.Data.PropertyId = p.Id;
                        df.DataEditor.Save();

                    }
                    m.Save();
                    umbraco.library.PublishSingleNode(m.Id);
                    

                    if (_emailonupdate == true)
                    {
                        MailMessage mm = new MailMessage();
                        mm.To.Add(new MailAddress(_emailto));
                        mm.Subject = _emailsubject;
                        mm.IsBodyHtml = true;

                        umbraco.cms.businesslogic.member.MemberType mtt = new umbraco.cms.businesslogic.member.MemberType(m.ContentType.Id);

                        StringBuilder sb = new StringBuilder();
                        sb.Append("<table>");

                        foreach (PropertyType pt in mtt.PropertyTypes)
                        {
                            sb.Append("<tr>");
                            sb.Append("<td>");
                            sb.Append("<b>" + pt.Name + "</b>");
                            sb.Append("</td>");
                            sb.Append("<td>");
                            sb.Append(m.getProperty(pt.Alias).Value.ToString());
                            sb.Append("</td>");
                            sb.Append("</tr>");
                        }

                        sb.Append("</table>");

                        mm.IsBodyHtml = true;
                        mm.Body = sb.ToString();

                        SmtpClient s = new SmtpClient();
                        s.Send(mm);


                    }

                    Response.Redirect(umbraco.library.NiceUrl(_redirect));



                }

            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message.ToString();
            }
        }
    }
}

